<script lang="tsx">
import { defineComponent, onMounted, ref } from 'vue';
import { ElButton, ElMessage } from 'element-plus';
import { $t } from '@vben/locales';
import { usePage } from '#/hooks/page/usePage';
import { Pencil, PencilRuler, Link, FilePenLine, FilePlus2 } from '@vben/icons';
import EditDrawer from './modules/competition-list/edit-drawer.vue';
import AgreementDrawer from './modules/competition-list/agreement-drawer.vue';
import IndexHomeDrawer from './modules/competition-list/index-home-drawer.vue';
import { getMatchInfoByConditionApi } from '#/api/competition/competition-list';
import dayjs from 'dayjs';
import { useClipboard } from '@vueuse/core';
export default defineComponent({
  name: 'CompetitionListPage',
  setup() {
    // 抽屉相关状态
    const showDrawer = ref(false);
    const drawerMode = ref<'add' | 'edit'>('add');
    const drawerFormData = ref<any>({});

    // 首页配置抽屉相关状态
    const showIndexHomeDrawer = ref(false);
    const indexHomeMode = ref<'add' | 'edit'>('add');
    const indexHomeFormData = ref<any>({});

    const { copy } = useClipboard();
    const competitionTypes = ref<any[]>([
      { label: $t('competition.innovationRace'), value: 0 },
      { label: $t('competition.challengeRace'), value: 1 }
    ]);

    // 表格列配置
    const columns = [
      { prop: 'title', label: $t('competition.competitionName'), minWidth: 200, showOverflowTooltip: true },
      { prop: 'introduction', label: $t('competition.competitionIntroduction'), minWidth: 300, showOverflowTooltip: true },
      {
        prop: 'matchType',
        label: $t('competition.competitionType'),
        minWidth: 120,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          const typeItem = competitionTypes.value.find(item => item.value === row.matchType);
          return typeItem ? typeItem.label : row.matchType || '--';
        }
      },
      { prop: 'insertUser', label: $t('competition.creator'), minWidth: 120, showOverflowTooltip: true },
      {
        prop: 'createTime',
        label: $t('common.createTimeTxt'),
        minWidth: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss');
        }
      },
    ];

    // 查询区配置
    const queryColumns = [
      { prop: 'title', label: $t('competition.competitionName'), type: 'input', placeholder: $t('common.inputPhTxt') },
      {
        prop: 'matchType',
        label: $t('competition.competitionType'),
        type: 'select',
        placeholder: $t('common.selectPhTxt'),
        options: competitionTypes.value
      },
    ];
    const API = {
      get:
        getMatchInfoByConditionApi,
    };

    // 操作按钮配置
    const commands = [
      {
        key: 'editIndex',
        width: 40,
        icon: Pencil,
        render: (row: any) => (
          <el-tooltip
            effect="dark"
            content={$t('competition.editHomePage')}
            show-after={600}
            placement="top"
          >
            <span class="edit-btn-wrapper">
              <el-button icon={PencilRuler} link onClick={() => handleEditIndex(row)}></el-button>
              {row.firstPageStatus === 0 && <span class="draft-dot"></span>}
            </span>
          </el-tooltip>
        ),
      },
      {
        key: 'copy',
        width: 40,
        icon: Pencil,
        render: (row: any) => (
          <el-tooltip
            effect="dark"
            content={$t('competition.copyHomePageLink')}
            show-after={600}
            placement="top"
          >
            <el-button icon={Link} link onClick={() => handleCopy(row)}></el-button>
          </el-tooltip>
        ),
      },
      {
        key: 'editInfo',
        width: 40,
        icon: Pencil,
        render: (row: any) => (
          <el-tooltip
            effect="dark"
            content={$t('competition.editCompetitionInfo')}
            show-after={600}
            placement="top"
          >
            <el-button icon={Pencil} link onClick={() => handleEdit(row)}></el-button>
          </el-tooltip>
        ),
      },
      {
        key: 'editAgreement',
        width: 40,
        icon: FilePenLine,
        render: (row: any) => (
          <el-tooltip
            effect="dark"
            content={row.agreementStatus ? $t('competition.editAgreement') : $t('competition.addAgreement')}
            show-after={600}
            placement="top"
          >
            <el-button icon={row.agreementStatus ? FilePenLine : FilePlus2} link onClick={() => handleAddAgreement(row, row.agreementStatus)}></el-button>
          </el-tooltip>
        ),
      },
    ];

    // 使用页面表格hooks
    const {
      render,
      getTableData,
      queryState
    } = usePage({
      operateProps: {
        fixed: 'right',
        width: '150px'
      },
      API,
      columns,
      queryColumns,
      commands,
    });

    // 新增按钮事件
    const handleAdd = () => {
      drawerMode.value = 'add';
      drawerFormData.value = {
        title: '',
        matchType: 0,
        domainName: '',
        introduction: '',
        cover: '',
        customerQuickCode: '',
        introduceVideo: '',
      };
      showDrawer.value = true;
    };

    // 复制按钮事件
    const handleCopy = async (row: any) => {
      const localhost = window.location.origin;
      const text = `${localhost}/competitionHomePage/competitionHomePageIndex?matchId=${row.id}`;
      await copy(text);
      ElMessage.success($t('competition.copySuccess'));
    };
    // 编辑按钮事件
    const handleEdit = (row: any) => {
      drawerMode.value = 'edit';
      if (row.draft) {
        drawerFormData.value = {
          ...JSON.parse(row.draft)
        };
      } else {
        drawerFormData.value = { ...row };
      }
      showDrawer.value = true;
    };

    // 抽屉确认事件
    const handleDrawerSuccess = () => {
      showDrawer.value = false;
      getTableData();
    };

    // 抽屉取消事件
    const handleDrawerCancel = () => {
      showDrawer.value = false;
      drawerFormData.value = {};
    };


    // 首页配置-编辑按钮事件（PencilRuler）
    const handleEditIndex = (row: any) => {
      indexHomeMode.value = 'edit';
      indexHomeFormData.value = { ...row };
      showIndexHomeDrawer.value = true;
    };

    // 首页配置抽屉 确认/取消
    const handleIndexHomeSuccess = () => {
      showIndexHomeDrawer.value = false;
      getTableData();
    };
    const handleIndexHomeCancel = () => {
      showIndexHomeDrawer.value = false;
      indexHomeFormData.value = {};
    };

    // 协议抽屉状态与事件
    const showAgreementDrawer = ref(false);
    const agreementMode = ref<'add' | 'edit'>('add');
    const agreementFormData = ref<any>({});

    const handleAddAgreement = (row: any, agreementStatus: number) => {
      if (agreementStatus === 0) {
        agreementMode.value = 'add';
        agreementFormData.value = { matchId: row.id, agreementName: '', agreementContent: '' };
        showAgreementDrawer.value = true;

      } else {
        agreementMode.value = 'edit';
        // 抽屉内查询协议详情
        agreementFormData.value = { matchId: row.id };
        showAgreementDrawer.value = true;
      }
    };
    const handleAgreementSuccess = () => {
      showAgreementDrawer.value = false;
      getTableData();
    };
    const handleAgreementCancel = () => {
      showAgreementDrawer.value = false;
      agreementFormData.value = {};
    };

    onMounted(() => {
    });

    return () => (
      <div>
        {render({
          header: (
            <ElButton type="primary" onClick={handleAdd}>
              {$t('competition.newCompetition')}
            </ElButton>
          ),
        })}
        <EditDrawer
          modelValue={showDrawer.value}
          formData={drawerFormData.value}
          mode={drawerMode.value}
          competitionTypes={competitionTypes.value}
          onUpdate:modelValue={(val: boolean) => showDrawer.value = val}
          onSuccess={handleDrawerSuccess}
          onCancel={handleDrawerCancel}
        />
        <AgreementDrawer
          modelValue={showAgreementDrawer.value}
          formData={agreementFormData.value}
          mode={agreementMode.value}
          onUpdate:modelValue={(val: boolean) => showAgreementDrawer.value = val}
          onSuccess={handleAgreementSuccess}
          onCancel={handleAgreementCancel}
        />
        <IndexHomeDrawer
          modelValue={showIndexHomeDrawer.value}
          formData={indexHomeFormData.value}
          mode={indexHomeMode.value}
          onUpdate:modelValue={(val: boolean) => (showIndexHomeDrawer.value = val)}
          onSuccess={handleIndexHomeSuccess}
          onCancel={handleIndexHomeCancel}
        />

      </div>
    );
  }
});
</script>

<style scoped>
:deep(.edit-btn-wrapper) {
  position: relative;
  display: inline-block;
  width: 38px;

  .draft-dot {
    position: absolute;
    top: 4px;
    right: 8px;
    width: 8px;
    height: 8px;
    background: #ff3b30;
    border-radius: 50%;
    z-index: 1;
  }
}
</style>
